import axios from "axios";
import { useEffect, useState } from "react";
import styles from "./Email.module.css";

export default function Email() {
  const [list, setList] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  const getlist = async () => {
    try {
      const userId = sessionStorage.getItem('userid');
      if (!userId) return;

      const { data } = await axios.get('http://localhost:3000/getContact', {
        params: { _id: userId }
      });
      
      setList(data.contact || []);
    } catch (error) {
      console.error('获取联系人失败:', error);
    } finally {
      setIsLoading(false);
    }
  };

  useEffect(() => {
    getlist();
  }, []);

  return (
    <div className={styles.emailContainer}>
      {isLoading ? (
        <div className={styles.loadingSkeleton}>
          {Array(5).fill(0).map((_, i) => (
            <div key={i} className={styles.skeletonItem}></div>
          ))}
        </div>
      ) : (
        <ul className={styles.contactList}>
          {list.map((item) => (
            <li key={item._id} className={styles.contactItem}>
              <div className={styles.avatarSection}>
                {item.head ? (
                  <img src={item.head} alt={item.name} className={styles.avatar} />
                ) : (
                  <div className={styles.initials}>{item.name?.charAt(0)?.toUpperCase() || '?'}</div>
                )}
              </div>
              
              <div className={styles.infoSection}>
                <h3 className={styles.name}>{item.name}</h3>
                {item.is ? (
                  <span className={styles.statusLabel}>已添加</span>
                ) : (
                  <div className={styles.buttonGroup}>
                    <button className={styles.addBtn}>添加</button>
                    <button className={styles.cancelBtn}>取消</button>
                  </div>
                )}
              </div>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}